package ivo.service.impl;

import ivo.action.CrrAction;
import ivo.dao.IWfmDao;
import ivo.dao.IWfmPptDao;
import ivo.pojo.AcarristPO;
import ivo.pojo.AeqptptPO;
import ivo.pojo.AeqptstPO;
import ivo.pojo.DcarrixfPO;
import ivo.pojo.StockerPO;
import ivo.service.ICrrService;
import ivo.tx.Amsheart.FbpbistolO;
import ivo.tx.Amsheart.FrpclmxfrO;
import ivo.tx.Amsheart.FrpiqcrrxO;
import ivo.tx.Amsheart.FrplststcO;
import ivo.tx.Amsheart.FrplwipeqO;
import ivo.util.HttpClientUtil;
import ivo.util.Requesturl;
import ivo.util.Util;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component("crrService")
public class CrrService implements ICrrService{
	private Logger logger = Logger.getLogger(CrrAction.class);
	private IWfmPptDao wfmPptDao;
	private IWfmDao wfmDao;
	private String outMsg=null;
	
	private static String _NORMAL = "0000000";
	/**
	 * 查询port上卡匣信息
	 * LDRQ:查询时否已有卡匣正在派送。若无则发送APWHTNXT，筛选可上port卡匣；若有则查询卡匣信息
	 * LDCM(BUSY):查询卡匣信息
	 * UDRQ:
	 * UDCM:
	 */
	@SuppressWarnings("deprecation")
	public AcarristPO queryCrrInfo(String eqpt_id,String port_id){
		Integer crr_cnt = 0;
		String DirectTransResult = "";
		String remark = "";
		AcarristPO crrInfo = new AcarristPO();
		AeqptptPO eqptpt = new AeqptptPO();
		AeqptstPO eqptst = new AeqptstPO();
		Map<String,String> eqptptMap=new HashMap<String,String>(); 
		eqptptMap.put("eqptID",eqpt_id);
		eqptptMap.put("portID",port_id);
		/**
		 * 查询机台port上卡匣信息
		 */
		crrInfo = wfmPptDao.selectCrrInfoOnPort(eqpt_id,port_id);
		if(crrInfo != null && crrInfo.getRouteID() !=null && !crrInfo.getRouteID().equals("")){
			if(crrInfo.getCrrStat().equals("INPR") &&
					crrInfo.getRouteID().substring(0, 1).equals("M")){//只有主途程卡匣，且已经入账时才去判断是否能够直传
				//查询port口类型
				eqptpt = wfmPptDao.selectEqptPt(eqptptMap);
				//查询派工设定
				eqptst = wfmPptDao.selectEqptSt(eqpt_id);
				if(eqptpt.getPortTyp().equals("L") || eqptpt.getPortTyp().equals("C")){
					if(eqptst.getForceRetLd().equals("Y")){
						crrInfo.setRemark("卡匣无法直传（机台自动派工\"LOADER/通用\"端设定为强制返回stocker）！");
					}else{
						DirectTransResult = CrrDirectTransResult(crrInfo,eqptptMap,eqptst.getrTimeL());
						crrInfo.setRemark(DirectTransResult);
					}
				}else{
					if(eqptst.getForceRetUl().equals("Y")){
						crrInfo.setRemark("卡匣无法直传（机台自动派工\"下货设备\"端设定为强制返回stocker）！");
					}else{
						DirectTransResult = CrrDirectTransResult(crrInfo,eqptptMap,eqptst.getrTimeL());
						crrInfo.setRemark(DirectTransResult);
					}
				}
			}else{
				crrInfo.setRemark("卡匣已经上port完成！");
			}
		}else{
			/**
			 * 查询正在搬送至port上的卡匣
			 */
			crrInfo = new AcarristPO();
			crrInfo = wfmPptDao.selectCrrInfoToPort(eqptptMap);
			if(crrInfo != null){
				if(!crrInfo.getLastXfrCmdRc().equals(_NORMAL)){
					crrInfo.setRemark("拒绝码为：" + crrInfo.getLastXfrCmdRc() + " 无法正常上port！");
				}else if(!crrInfo.getLastLocRptRc().equals(_NORMAL)){
					crrInfo.setRemark("TSC代码为：" + crrInfo.getLastLocRptRc() + " 无法正常上port！");
				}else{
					String frEqpt = crrInfo.getFrEqptID();
					String toEqpt = crrInfo.getToEqptID();
					String loadTime = crrInfo.getRsv_timestamp();
					
//					获取properties文件的key（1AS01/1AS02）
					String bay_ids = wfmPptDao.rtnportCrrUseTime(frEqpt, toEqpt);
					
//					根据bay_ids获取该bay之间搬送耗时以及in/out的时间
					String use_time = Util.readLoadCrrUseTimeProperties(bay_ids);
					String in_out = Util.readLoadCrrUseTimeProperties("in/out");
					
//					use_time转为妙 , 然后加上in/out的时间
					int time_s = Integer.valueOf(use_time.split(":")[0])*60 + Integer.valueOf(use_time.split(":")[1]) + Integer.valueOf(in_out);
					
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date date = null;
					
//					将读取的properties中的维护的时间转为S，将posChgTimestamp转为java.util.date类型，将时间相加，获得预计上port时间
					try {
						date = simpleDateFormat.parse(loadTime);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					date.setSeconds(date.getSeconds()+time_s);
					
//					将已经计算好的java.util.date类型的时间转换成String类型，返回到前台
					String load_time = simpleDateFormat.format(date);
					
					crrInfo.setRemark("卡匣正在进行上port搬送......预计上port时间:"+load_time);
				}
			}else{
				/**
				 * 查询正在下port的卡匣
				 */
				crrInfo = new AcarristPO();
				crrInfo = wfmPptDao.selectCrrInfoFrPort(eqptptMap);
				if(crrInfo != null){
					if(!crrInfo.getLastXfrCmdRc().equals(_NORMAL)){
						crrInfo.setRemark("拒绝码为：" + crrInfo.getLastXfrCmdRc() + " 无法正常下port！");
					}else if(!crrInfo.getLastLocRptRc().equals(_NORMAL)){
						crrInfo.setRemark("TSC代码为：" + crrInfo.getLastLocRptRc() + " 无法正常下port！");
					}else{
						crrInfo.setRemark("卡匣正在下port......");
					}
				}else{//未产生搬送指令时，发送WHTNXT，筛选卡匣
//					crrInfo = new AcarristPO();
//					ApwhtnxtI apwhtnxtI = new ApwhtnxtI();
//					apwhtnxtI.setTrx_id("APWHTNXT");
//					apwhtnxtI.setType_id("I");
//					apwhtnxtI.setEqpt_id(eqpt_id);
//					apwhtnxtI.setPort_id(port_id);
//					apwhtnxtI.setFunc_id("LODREQ");
//					.
//					String xml = XmlUtil.object2xml(apwhtnxtI);
//			        String outTrx = mqRouter.sendMessage(xml);
//			        ApwhtnxtO apwhtnxtO = (ApwhtnxtO)XmlUtil.xml2object(outTrx, new ApwhtnxtO());
//			        if(apwhtnxtO.getRtn_code().equals(_NORMAL)){
//			        	System.out.println("卡匣数量：" + apwhtnxtO.getCrr_cnt());
//			        	for(int i =0; i < Integer.parseInt(apwhtnxtO.getCrr_cnt(), 10); i++){
//			        		if(apwhtnxtO.getOary().get(i).getMask_reason().equals("0000")){
//			        			remak = remak + apwhtnxtO.getOary().get(i).getCrr_id() +"\n";
//			        			crr_cnt = crr_cnt+1;
//			        		}
//			        	}
//			        	crrInfo.setRemark("符合搬送条件的卡匣数量为:" + crr_cnt
//			        			+ "\n" + remak);
//			        }else{
//						crrInfo.setRemark(apwhtnxtO.getRtn_mesg());
//			        }
				}
			}
		}
		return crrInfo;
	}
	
	private String CrrDirectTransResult(AcarristPO crrInfo,
			Map<String, String> eqptptMap,String waitTime){
		InputStream in = null;
		String result = "";
		String unloadTime1 = "";
		String unloadTime2 = "";
		int runtime1 = 0;
		int runtime2 = 0;
		int waitProcCnt = 0;
		int defaultTime = 1800;//每片默认run货时间(s)
		Properties prop =  new  Properties();
		List<AcarristPO> crrList = new ArrayList<AcarristPO>();
		List<AcarristPO> crrList2 = new ArrayList<AcarristPO>();
		List<AeqptptPO> eqptList = new ArrayList<AeqptptPO>();
		Map<String,String> strMap=new HashMap<String,String>(); 
		AeqptptPO eqptpt = new AeqptptPO();
		String cr_eqpt_3,cr_eqpt_5;
		String nx_eqpt_3,nx_eqpt_5;
		/**
		 * 获取上游机台设定时间
		 */
		in =  WfmService.class.getResourceAsStream("/runtime.properties");
		try {                                                                                           
			prop.load(in);                                                                            
		    cr_eqpt_3=eqptptMap.get("eqptID").substring(2,5); 
		    cr_eqpt_5=eqptptMap.get("eqptID").substring(2);
			if(cr_eqpt_3.equals("CVD")){ 
				 runtime1 =Integer.parseInt(prop.getProperty(cr_eqpt_3+crrInfo.getOpeID().trim()));	
			}else if(cr_eqpt_3.equals("WET")){                                                                                         
				if(cr_eqpt_5.equals("WET510")||cr_eqpt_5.equals("WET520")){ 
					runtime1 =Integer.parseInt(prop.getProperty(cr_eqpt_5));                  
				}else {    
					runtime1 =Integer.parseInt(prop.getProperty(cr_eqpt_3));               
				}                                                                                                                                                                          
			}else{                                                                                    
				runtime1 =Integer.parseInt(prop.getProperty(cr_eqpt_3)); 
			}                                                                                         
			in.close();                                                                               
		} catch (Exception e) {//读取异常，默认值                                                   
			runtime1 = defaultTime;                                                                   
		}
		unloadTime1 = Util.getChgTime(crrInfo.getPosChgTimestamp(),runtime1);
		result = "卡匣预计" + unloadTime1 + "制程结束！";
		/**
		* 查询上游机台上卡匣信息
		*/
		eqptList = wfmPptDao.selectEqpt(crrInfo.getEqptgId());
		for(int j=0; j<eqptList.size(); j++){
			nx_eqpt_3=eqptList.get(j).getEqptID().substring(2,5);
			nx_eqpt_5=eqptList.get(j).getEqptID().substring(2);
			crrList2 = wfmPptDao.selectCrrInfoOnPortList(eqptList.get(j).getEqptID());
			for(int k=0; k<crrList2.size(); k++){
				try {                                                                                           
					prop.load(in);                                                                            
					if(nx_eqpt_3.equals("CVD")){                                                 
						runtime1 =Integer.parseInt(prop.getProperty(nx_eqpt_3+crrList2.get(k).getOpeID()));	
					}else if(nx_eqpt_3.equals("WET")){                                                                                         
						if(nx_eqpt_5.equals("WET510")||nx_eqpt_5.equals("WET520")){ 
							runtime2 =Integer.parseInt(prop.getProperty(nx_eqpt_5));                  
						}else {    
							runtime2 =Integer.parseInt(prop.getProperty(nx_eqpt_3));               
						}                                                                                                                                                                          
					}else{                                                                                    
						runtime2 =Integer.parseInt(prop.getProperty(nx_eqpt_3)); 
					}                                                                                         
					in.close();                                                                               
				} catch (Exception e) {//读取异常，默认值                                                   
					runtime2 = defaultTime;                                                                   
				}
				unloadTime2 = Util.getChgTime(crrList2.get(k).getPosChgTimestamp(),runtime2);
				if(Util.CompareTime(unloadTime1, unloadTime2,waitTime)){
					result = result + "制程结束可能直传";
					return result;
				}
			}
		}
		return result;	 
			
		/**
		 * 查询下有机台信息
		 */	
	}
	
	
	@SuppressWarnings("deprecation")
	public List<DcarrixfPO> loadCrrSortInfo(){
		List<DcarrixfPO> dcarrixfPOList = new ArrayList<DcarrixfPO>();
		dcarrixfPOList = wfmPptDao.loadCrrSortInfo();
		Date nowDate = new Date();
		if (!dcarrixfPOList.isEmpty()) {
			for (DcarrixfPO dcarrixfPO:dcarrixfPOList) {
				String frEqpt = dcarrixfPO.getFr_eqpt_id();
				String toEqpt = dcarrixfPO.getTo_eqpt_id();
				String loadTime = dcarrixfPO.getRsv_timestamp();
				if (Util.isSpaceCheck(frEqpt) || Util.isSpaceCheck(toEqpt)) {
					continue;
				}

//				获取properties文件的key（1AS01/1AS02）
				String bay_ids = wfmPptDao.rtnLoadCrrUseTime(frEqpt, toEqpt);
				
//				根据bay_ids获取该bay之间搬送耗时以及in/out的时间
				String use_time = Util.readLoadCrrUseTimeProperties(bay_ids);
				String in_out = Util.readLoadCrrUseTimeProperties("in/out");
				
//				use_time转为妙 , 然后加上in/out的时间
				int time_s = Integer.valueOf(use_time.split(":")[0])*60 + Integer.valueOf(use_time.split(":")[1]) + Integer.valueOf(in_out);
				
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = null;
				
//				将读取的properties中的维护的时间转为S，将posChgTimestamp转为java.util.date类型，将时间相加，获得预计上port时间
				try {
					date = simpleDateFormat.parse(loadTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
//				计算delay时间确定显示何种颜色
				long l = nowDate.getTime()-date.getTime();
				long min=l/(60*1000);
				
				if (min > 30) {
					dcarrixfPO.setColor("red");
				}else if (min > 15) {
					dcarrixfPO.setColor("blue");
				}else {
					dcarrixfPO.setColor("");
				}
				
				date.setSeconds(date.getSeconds()+time_s);
				
//				将已经计算好的java.util.date类型的时间转换成String类型，返回到前台
				String load_time = simpleDateFormat.format(date);
				
				dcarrixfPO.setLoad_timestamp(load_time);
			}
			
//			按照即将到达机台的时间排序
			Collections.sort(dcarrixfPOList,new Comparator<DcarrixfPO>(){
				public int compare(DcarrixfPO arg0, DcarrixfPO arg1) {
	                return arg0.getLoad_timestamp().compareTo(arg1.getLoad_timestamp());
	            }
			});  
			
//			测试
//			for (DcarrixfPO dcarrixfPO:dcarrixfPOList) {
//				System.out.println(dcarrixfPO.getLoad_timestamp()+"####"+dcarrixfPO.getColor());
//			}
		}
		return dcarrixfPOList;
	}
	
	@Override
	public List<StockerPO> isBusy() {
		List<StockerPO> stockerPOList = new ArrayList<StockerPO>();
		List<DcarrixfPO> dcarrixfPOList = new ArrayList<DcarrixfPO>();
		dcarrixfPOList = wfmPptDao.loadCrrSortInfo();
		Map<String, Integer> stkMap = new HashMap<String, Integer>();
		for(DcarrixfPO dcarrixfPO : dcarrixfPOList){
			String fr_eqpt_id = dcarrixfPO.getFr_eqpt_id();
			String to_eqpt_id = dcarrixfPO.getTo_eqpt_id();
			//BAY_ID
			String bay_ids = wfmPptDao.rtnLoadCrrUseTime(fr_eqpt_id, to_eqpt_id);
			String [] bay_array = bay_ids.split("/");
			
			if (bay_array[0].equals(bay_array[1])) {
				
				if (stkMap.containsKey(bay_array[0])) {
					stkMap.put(bay_array[0], stkMap.get(bay_array[0])+1);
				} else {
					stkMap.put(bay_array[0], 1);
				}
				
			}else {
				
				if (stkMap.containsKey(bay_array[0])) {
					stkMap.put(bay_array[0], stkMap.get(bay_array[0])+3);
				} else {
					stkMap.put(bay_array[0], 3);
				}
				
				if (stkMap.containsKey(bay_array[1])) {
					stkMap.put(bay_array[1], stkMap.get(bay_array[1])+1);
				} else {
					stkMap.put(bay_array[1], 1);
				}
			}
		}
		
		for (Entry<String, Integer> ent : stkMap.entrySet()){
			StockerPO stk = new StockerPO();
			
			if (ent.getKey().equals("1AS18")) {
				continue;
			}
			
			String stk_id = Util.Bay2Stk(ent.getKey());
			//获取STK爆仓信息
			int use_cnt = wfmPptDao.stkIsFull(stk_id);
			int thres_hold = wfmPptDao.stkThresHold(stk_id);
			if (use_cnt < thres_hold) {
				stk.setIsFull("未爆仓");
				stk.setExt_1("#007799");
			} else {
				stk.setIsFull("已爆仓");
				stk.setExt_1("#CC0000");
			}
			
			if("#007799".equals(stk.getExt_1())){
				if (ent.getValue()>=30) {
					stk.setExt_1("#CC0000");
				}
			}
			int stkptn=0;
			if(stk_id.equals("C1STK100") || stk_id.equals("C1STK200")){
				 stkptn =Integer.parseInt(stk_id.substring(5));
			}
			else{
				stkptn=Integer.parseInt(stk_id.substring(2));
			}
			stk.setUse_cnt(use_cnt);
			stk.setThres_hold(thres_hold);
			stk.setStk_id(stk_id);
			stk.setUse_time(ent.getValue().toString());
			stk.setStkptn(stkptn);
			
			//TODO:target=30;
			//stk.setExt_1(1);
			
			stockerPOList.add(stk);	
		}

//		对List进行排序
		Collections.sort(stockerPOList,new Comparator<StockerPO>(){
			public int compare(StockerPO arg0, StockerPO arg1) {
                return Integer.valueOf(arg0.getStkptn()).compareTo(Integer.valueOf(arg1.getStkptn()));
            }
		});
		return stockerPOList;
	}
	
	@Override
	public List<AcarristPO> selectAllCrrInfoOnPort(){
		return wfmPptDao.selectAllCrrInfoOnPort();
	}
	
	public IWfmPptDao getWfmPptDao() {
		return wfmPptDao;
	}

	@Resource
	public void setWfmPptDao(IWfmPptDao wfmPptDao) {
		this.wfmPptDao = wfmPptDao;
	}
	
	public IWfmDao getWfmDao() {
		return wfmDao;
	}
	
	@Resource
	public void setWfmDao(IWfmDao wfmDao) {
		this.wfmDao = wfmDao;
	}
	/*//更新对话框信息
	public void update(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FRPCLMXFR",jsonObj);
	}
	//初始化stocker
	public void initStocker(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FRPLSTSTC",jsonObj);
	}
	//初始化stocker位置信息
	public void initstkpatition(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FRPLSTSTC",jsonObj);
	}
	//初始化卡搬送匣信息
	public void queryCrrxfrInfo(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FRPIQCRRX",jsonObj);
	}
	//初始化目的机台信息
	public void inittoTool(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FBPBISTOL",jsonObj);
	}
	//初始化到目的端口信息
	public void inittoToolPort(JSONObject jsonObj) {
		// TODO Auto-generated method stub
		HttpClientUtil.postMethodForMES("mes-dx-web-rtd/sendMsg.do","FRPLWIPEQ",jsonObj);
	}
*/

	//手动上报卡匣信息的操作
		public String update(String strMsg) {
			// TODO Auto-generated method stub
			outMsg=HttpClientUtil.postMethodForMES(Requesturl.getUrl(), "FRPCLMXFR", strMsg);
			return outMsg;
		}

		public List<StockerPO> initstkpatition(String stocker_id) {
			// TODO Auto-generated method stub
			return wfmPptDao.selestkpati(stocker_id);
		}

		public List<DcarrixfPO> queryCrrxfrInfo(String crr_id) {
			// TODO Auto-generated method stub
			return wfmPptDao.seleTxrInfo(crr_id);
		}

		public List<AeqptstPO> inittoTool(String unitTyp) {
			// TODO Auto-generated method stub
			return wfmPptDao.selectTool(unitTyp);
		}

		public List<AeqptptPO> inittoToolPort(String root_tool_id) {
			// TODO Auto-generated method stub
			return wfmPptDao.selectToolPort(root_tool_id);
		}

		public List<StockerPO> initStocker() {
			return wfmPptDao.selectStockerInfo();
		}


	public String getOutMsg() {
		return outMsg;
	}

	public void setOutMeg(String outMsg) {
		this.outMsg = outMsg;
	}

}
